import classNames from "classnames";
import { FC, useEffect, useMemo, useRef } from "react";
import Swiper from "swiper";
import "swiper/css";
import style from "./index.scss";

interface IProps {
  list: IFilm[];
  film: IFilm;
  onChange: (index: number) => void;
}

const FilmList: FC<IProps> = ({ list, film, onChange }) => {
  const box = useRef(null);

  const initialSlide = useMemo(() => {
    // 从 list 中找到 film 的下标
    return list.findIndex((item) => item.filmId === film.filmId);
  }, [list, film]);

  useEffect(() => {
    new Swiper(box.current!, {
      // 初始化选中的下标
      initialSlide,
      // 一个可视区域显示几个子元素
      slidesPerView: 4,
      // slide 之间的间隔
      spaceBetween: 10,
      // 控制当前激活的显示在中间
      centeredSlides: true,
      // 点击可以切换
      slideToClickedSlide: true,

      on: {
        slideChange: (swiper) => {
          // swiper 是 new Swiper 的实例对象
          // console.log("轮播图切换了", swiper);
          // setCurActiveIndex(swiper.activeIndex);

          // 调用 父组件传递过来的 onChange
          onChange(swiper.activeIndex);
        },
      },
    });
  }, []);

  return (
    <div ref={box} className={classNames(["swiper-container", style.box])}>
      {film && (
        <div
          className={style.bg}
          style={{
            backgroundImage: `url(${film.poster})`,
          }}
        ></div>
      )}

      <div className="swiper-wrapper">
        {list.map((item) => {
          return (
            <div
              key={item.filmId}
              className={classNames(["swiper-slide", style.slide])}
            >
              <img className={style.img} src={item.poster} alt="" />
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default FilmList;
